package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"time"
	"zg3/day13/api/request"
	"zg3/day13/global"
	"zg3/day13/internal/dao"
	"zg3/day13/internal/model"
	"zg3/day13/pkg"
)

func UserLogin(c *gin.Context) {
	var req request.UserLogin
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	if global.Rdb.Get(context.Background(), "smsCodeLogin"+req.Phone).Val() != req.Code {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "短信验证码错误",
			"data": false,
		})
		return
	}

	user := dao.FindUser(req.Phone)
	if user.Id == 0 {
		dao.Create(&model.User{
			Phone: req.Phone,
		})
		token, _ := pkg.NewJWT("2210a").CreateToken(pkg.CustomClaims{
			ID: user.Id,
		})

		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "注册登录成功",
			"data": token,
		})
		return
	} else {
		token, _ := pkg.NewJWT("2210a").CreateToken(pkg.CustomClaims{
			ID: user.Id,
		})

		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "登录成功",
			"data": token,
		})
		return
	}
}

func SendSms(c *gin.Context) {
	var req request.SendSmsReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	code := rand.Intn(9000) + 1000
	//sms, _ := pkg.SendSms(req.Phone, strconv.Itoa(code))
	//if *sms.Body.Code != "OK" {
	//	c.JSON(http.StatusOK, gin.H{
	//		"code": 500,
	//		"msg":  *sms.Body.Message,
	//		"data": false,
	//	})
	//	return
	//}

	global.Rdb.Set(context.Background(), "smsCode"+req.Source+req.Phone, code, time.Minute*10)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "短信发送成功",
		"data": true,
	})
	return
}

func UserAttention(c *gin.Context) {
	var req request.UserAttention
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.FindId(req.FolloweeId, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
			"data": false,
		})
		return
	}
	attention := model.UserFollower{
		FollowerId: c.GetUint("userId"),
		FolloweeId: int64(req.FolloweeId),
	}
	dao.Create(&attention)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "关注成功",
		"data": attention,
	})
	return
}
